package com.doubledr.light_lock.utils;

import android.util.Base64;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

//进行加密和解密的工具类，负责对文件进行加密和解密
public class FileManager {
    /*
    1.源文件的路径
    2.目标文件路径
    3.进度回调函数
     */
    public static   boolean  enCryptFile(String sourceFilePath, String targetFilePath,int pwd, FileProgress cb){

        try {
            FileOutputStream fout = new FileOutputStream(new File(targetFilePath));
            fout.write(0xee);//加密文件标志
            //读取源文件
            File sFile = new File(sourceFilePath);
            long totalLength = sFile.length();

            String fileExt = getExtensionName(sourceFilePath);
            byte[] extBytes = fileExt.getBytes();
            int extLength = extBytes.length;
            //把后缀名写入文件隐藏起来
            fout.write(int2BytesArray(extLength));
            fout.write(extBytes);

            FileInputStream fin = new FileInputStream(sFile);
            int sdata = fin.read();
            long enCount = 0;
            while (sdata!=-1){
                //对每个字节进行异或操作
                sdata = sdata^pwd;
                fout.write(sdata);
                enCount++;
                long percent = 100*enCount/totalLength;
                if(cb!=null){
                    if(percent%20 == 0){
                        cb.getProgress((int)percent);
                    }
                }
                sdata = fin.read();
            }
            fin.close();
            fout.close();

        }catch (Exception e){
            System.out.println(e.getMessage());
            cb.getProgress(-1);
            return  false;
        }
        return true;
    }
    /*
    解密文件
     */
    public static   boolean  deCryptFile(String sourceFilePath, String targetFilePath,int pwd, FileProgress cb){
        try {
            //读取源文件
            File sFile = new File(sourceFilePath);
            long totalLength = sFile.length();
            //读取文件头4个字节

            //String fileExt = getExtensionName(sourceFilePath);
            //byte[] extBytes = fileExt.getBytes();
            //int extLength = extBytes.length;
            //把后缀名写入文件隐藏起来
            //fout.write(extLength);
            //fout.write(extBytes);

            FileInputStream fin = new FileInputStream(sFile);
            int file_flag = fin.read();
            if(file_flag != 0xee){
                cb.getProgress(-1);
                return false;
            }
            byte[] extLengthBytes = new byte[4];
            fin.read(extLengthBytes,0,4);
            int extLength = byteArray2Int(extLengthBytes);
            byte[] extBytes = new byte[extLength];
            fin.read(extBytes,0,extLength);
            String exString = new String(extBytes);


            FileOutputStream fout = new FileOutputStream(new File(targetFilePath+"/"+getFileNameNoEx(sourceFilePath)+"."+exString));

            int sdata = fin.read();
            long enCount = 4+extLength;
            while (sdata!=-1){
                //对每个字节进行异或操作
                sdata = sdata^pwd;
                fout.write(sdata);
                enCount++;
                long percent = 100*enCount/totalLength;
                if(cb!=null){
                    if(percent%20 == 0){
                        cb.getProgress((int)percent);
                    }
                }
                sdata = fin.read();
            }
            fin.close();
            fout.close();

        }catch (Exception e){
            System.out.println(e.getMessage());
            cb.getProgress(-1);
            return  false;
        }
        return true;
    }
    //加密纯文本
    public static String encryptTxt(String strTxt,int pwd){

        String rs = "";
        try
        {
            rs = Base64.encodeToString(strTxt.getBytes(),Base64.DEFAULT);
            byte[] strBytes = rs.getBytes();
            for(int i=0;i<strBytes.length;i++){
                strBytes[i] = (byte) (strBytes[i]^pwd);
            }
            rs = new String(strBytes);
        }
        catch (Exception ex){

        }

        return rs;
    }
    //解密纯文本
    public static String decryptTxt(String strTxt,int pwd){
        String rs = "";
        try
        {
            byte[] strBytes = strTxt.getBytes("UTF-8");
            for(int i=0;i<strBytes.length;i++){
                strBytes[i] = (byte) (strBytes[i]^pwd);
            }
            rs = new String(Base64.decode(strBytes,Base64.DEFAULT));

        }
        catch (Exception ex){

        }

        return rs;
    }
    //把文件压缩成zip包
    private static boolean zipFile(final File srcFile, String rootPath, final ZipOutputStream zos, final String comment) throws IOException {
        rootPath = rootPath + File.separator + srcFile.getName();
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcFile));
            ZipEntry entry = new ZipEntry(rootPath);
            entry.setComment(comment);
            zos.putNextEntry(entry);
            byte buffer[] = new byte[512];
            int len;
            while ((len = is.read(buffer, 0, 512)) != -1) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
        } finally {
            is.close();
        }
        return true;
    }
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            int dot2 = filename.lastIndexOf('/');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(dot2+1, dot);
            }
        }
        return filename;
    }
    public static int byteToInt(byte[] bytes){
        String s = new String(bytes);
        return Integer.parseInt(s);
    }
    public static byte[] int2BytesArray(int n) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (n >> (24 - i * 8));
        }
        return b;
    }
    public static int byteArray2Int(byte[] b) {
        int a = (((int) b[0]) << 24) + (((int) b[1]) << 16) + (((int) b[2]) << 8) + b[3];
        if (a < 0) {
            a = a + 256;
        }
        return a;
    }
}
